<?php

require_once dirname(__FILE__) . '/../phpsmart.class.php' ;

$schema = '

    show:
      + show_form
      -> ok     check
      
    check:
      + check_form
      -> succes send
      -> errors show
      
    send:
      + send_form
      + show_succes
  
' ;

$sm = new phpSmart();
$sm->load($schema);

//-------------------------------------------------------------------------


function show_form($obj,$pass) {
  
  $ok_event_hidden = $obj->getNextEvent('ok','form') ;
  
  if ( empty($pass) ) $pass = array() ;
  
  echo "<form method=\"post\">";
  echo $ok_event_hidden;
  echo "First Name <input type=\"text\" name=\"fname\" value=\"".htmlspecialchars($pass['values']['fname'])."\"> {$pass['errors']['fname']}<br />";
  echo "Last Name <input type=\"text\" name=\"lname\" value=\"".htmlspecialchars($pass['values']['lname'])."\"> {$pass['errors']['lname']}<br />";
  echo "<input type=\"submit\" name=\"Submit\">";
  echo "</form>";

}

function check_form($obj,$pass) {
  
  $errors = array() ;
  
  $formvars['values'] = array_map('stripslashes',$_POST) ;
  
  if ( empty($formvars['values']['fname']) ) $errors['fname'] = 'field required' ;
  if ( empty($formvars['values']['lname']) ) $errors['lname'] = 'field required' ;

  $formvars['errors'] = $errors ;
  
  // default next event
  $obj->setNextEvent('errors',$formvars);
  
  if ( empty($errors) )
    $obj->setNextEvent('succes',$formvars);
}

function send_form($obj,$pass) {
  
  $to        = "to@domain.com" ; // CHANGE MAIL ADRESS FOR TEST !!!
  $subject   = "Contact form" ;
  $additional_headers    = "From: {$to}" ;
  $additional_parameters = "-f{$to}" ;
  
  $message = "First Name: " . htmlspecialchars($pass['values']['fname']) . "\n"
           . "Last Name: ".htmlspecialchars($pass['values']['lname']) . "\n" ;
  
  if ( "to@domain.com" != $to ) {
    mail ($to,$subject,$message,$additional_headers,$additional_parameters) ;
  }

}

function show_succes($obj) {
  
  echo "successful form sended.<br />Thanks<br /><br />" ;
  echo "<a href=\"".basename(__FILE__)."\">back</a><br />" ;
  
}
